// bim-1302331233.cos.ap-chengdu.myqcloud.com/BM202311/Model/
// http://bim-1302331233.cos.ap-chengdu.myqcloud.com/ezBridge/dist/index.html
// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const COS = require("cos-nodejs-sdk-v5");
const fs = require("fs");
const path = require("path");

function walkDir(dirPath) {
  const rootDirLength = dirPath.length + 1;
  const files = [];
  function _walkDir(dirPath) {
    fs.readdirSync(dirPath).forEach((file) => {
      const filePath = path.join(dirPath, file);
      const stat = fs.statSync(filePath);
      if (stat.isDirectory()) {
        _walkDir(filePath); // 递归遍历子目录
      } else {
        files.push(filePath.slice(rootDirLength).replace(/\\/g, "/"));
      }
    });
  }
  _walkDir(dirPath);
  console.log(files);
  return files;
}

const cosConfig = {
  SecretId: process.env.COS_SECRET_ID, // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
  SecretKey: process.env.COS_SECRET_KEY, // 推荐使用环境变量获取；用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
};
const cos = new COS(cosConfig);

async function uploadFileToCOS(filePath, objectName) {
  const result = await cos.putObject({
    Bucket: process.env.COS_APP_ID,
    Region: "ap-chengdu",
    Key: objectName,
    Body: fs.createReadStream(filePath),
  });
  console.log(result.Location);
  return result;
}

function verify() {
  cos.getBucket(
    {
      Bucket: process.env.COS_APP_ID,
      Region: "ap-chengdu",
      Prefix,
    },
    (err, data) => {
      console.log(err || data.Contents);
    }
  );
}

function doUpload({ src, dest }, uploadMode = 1) {
  if (uploadMode) {
    walkDir(src).forEach((item) => {
      uploadFileToCOS(`${src}/${item}`, `${dest}/${item}`);
    });
    // verify();
  } else {
    verify();
  }
}

{
  // ezBridge
  let releaseDirs = [
    // { src: `D:/Develop/GitRepos/ezBridgeNext/dist`, dest: `ezBridge/dist` },
    // {
    //   src: `D:/Develop/GitRepos/ezBridgeNext/assets/template`,
    //   dest: `assets/template`,
    // },
    {
      src: `D:/Develop/GitRepos/ez-bridge-desktop/assets`,
      dest: `ezBridge/dist`,
    },
    // {
    //   src: `D:/Develop/GitRepos/ez-bridge-desktop/dist/help`,
    //   dest: `ezBridge/dist/help`,
    // },
    // {
    //   src: `D:/Develop/GitRepos/ezBridgeNext/assets/ezBridge`,
    //   dest: `assets/ezBridge`,
    // },
    // {
    //   src: `D:/Develop/GitRepos/ez-bridge-desktop/test`,
    //   dest: `ezBridge/dist`,
    // },
  ];
  let uploadMode = 1;

  releaseDirs.forEach((item) => {
    doUpload(item, uploadMode);
  });
}
